package core;

import java.io.Serializable;

import infrastructure.exceptions.LoginException;
import infrastructure.exceptions.operations.OperationException;
import inftrastructure.exceptions.ClientRuntimeException;
import dal.User;
import remote.Connection;
import remote.RemoteInvocation;
import server.IServerFacade;
import server.IServerSession;

public class ServerFacade implements IServerFacade {

	/** Keeps connection to the remote side*/
	protected Connection remoteConnection;
	
	/** Keeps server session*/
	protected ServerSession session;
	
	/** Keeps logged in user*/
	private User loggedInUser;
	
	
	public ServerFacade(Connection connectionToServer){
		remoteConnection = connectionToServer;		
		session = new NonLoggedInServerSession(-1);
		loggedInUser = null;
	}
	
	@Override
	public User getLoggedInUser() throws OperationException {
		if (null != loggedInUser){
			return loggedInUser;
		}else{
			throw new OperationException("Not logged in to the session");
		}
	}

	

	@Override
	public IServerSession logon(String userName,String password) throws LoginException {
		
		RemoteInvocation invoker;
		try {
			invoker = new RemoteInvocation(this.getClass(),
					this.getClass().getMethod("logon", new Class<?>[]{String.class,String.class}),
					session.getSessionId(), new Serializable[]{userName,password});
		} catch(Exception ex){
			throw new ClientRuntimeException("Bug !!!",ex);
		}	
	
		session = remoteConnection.invoke(invoker);		
		this.loggedInUser = session.getSessionUser();
		session.setServerAccess(this);
		return session;
		
		
	}

	@Override
	public void logout() {
		
		RemoteInvocation invoker;
		try {
			invoker = new RemoteInvocation(this.getClass(),
					this.getClass().getMethod("logout", new Class<?>[]{}),
					session.getSessionId(), new Serializable[]{});
		} catch(Exception ex){
			throw new ClientRuntimeException("Bug !!!",ex);
		}	
	
		session = new NonLoggedInServerSession(-1);
		remoteConnection.invoke(invoker);
		
	}

}
